/*
 * Copyright 2014 HarryKim.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package opera.common.net;

import handling.mina.MapleCodecFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.buffer.SimpleBufferAllocator;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author HarryKim
 */
public class ClientListener {
    
    private IoAcceptor acceptor;
    private final ServerHandler handler;
    private final InetSocketAddress inetAddress;
    
    private static final Logger Log = LoggerFactory.getLogger(ClientListener.class);

    public ClientListener(ServerHandler handler, InetSocketAddress inetAddress) {
        this.handler = handler;
        this.inetAddress = inetAddress;
    }

    public IoAcceptor getAcceptor() {
        return acceptor;
    }

    public ServerHandler getHandler() {
        return handler;
    }

    public InetSocketAddress getInetAddress() {
        return inetAddress;
    }
    
    public void bind() {
        try {
            IoBuffer.setUseDirectBuffer(false);
            IoBuffer.setAllocator(new SimpleBufferAllocator());
            acceptor = new NioSocketAcceptor();
            ((SocketSessionConfig) acceptor.getSessionConfig()).setTcpNoDelay(true);
            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
            acceptor.getFilterChain().addLast("codec", (IoFilter) new ProtocolCodecFilter(new MapleCodecFactory()));
            acceptor.setHandler(handler);
            acceptor.bind(inetAddress);
            Log.info("Success to bind {} Server on {}", handler.getServerType().toString(), inetAddress.toString());
        } catch (IOException e) {
            Log.error("Fail to bind " + handler.getServerType().toString() + " Server on " + inetAddress.toString(), e);
        }
    }
    
}
